#import "JokeManager.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJsonParser.h"
#import "JokeModel.h"
#import "JokeReplyModel.h"
#import "DBManager.h"
#import "UserManager.h"

@implementation JokeManager

@synthesize sortIndex, listShow, dbSort, gettingNext, gettingNew;

static float THUMBNAILWIDTH = 202.00;
static float THUMBNAILHEIGHT = 140.00;
static int DEFAULTLIMIT = 10;
static int LOCALLIMIT = 50;

-(id)initWithSort:(int)pSortIndex :(NSString *)pDBsort :(NSString *)pHTTPsort :(id<JokeManagerDelegate>) pDelegate {
    self = [super init];
    if (self) {
        sortIndex = pSortIndex;
        dbSort = pDBsort;
        httpSort = pHTTPsort;
        delegate = pDelegate;
        backIndex = 0;
        listShow = [[NSMutableArray alloc] init];
        setShow = [[NSMutableSet alloc] init];
        listNext = [[NSMutableArray alloc] init];
        dicLocal = [[NSMutableDictionary alloc] init];
        started = NO;
        gettingNew = NO;
        gettingNext = NO;
        [[DBManager sharedInstance] createJokeTable:dbSort];
        NSMutableArray *listAll = [[[DBManager sharedInstance] getAllJokeSummary:dbSort] retain];
        NSMutableArray *ids2Del = [[NSMutableArray alloc] init];
        int localCount = 0;
        for( int index = 0; index<listAll.count; ++index ){
            JokeModel *one = [listAll objectAtIndex:index];
            if( ++localCount <= LOCALLIMIT ){
                [dicLocal setObject:one forKey:one.jokeId];
                [listShow addObject:one];
                [setShow addObject:one.jokeId];
            }else{
                [ids2Del addObject:one.jokeId];
            }
        }
        if( ids2Del.count > 0 ){
            [[DBManager sharedInstance] deleteJokes:dbSort :ids2Del];
        }
        Log(@"local(%@): all/del/left : %d/%d/%d",dbSort,listAll.count,ids2Del.count,dicLocal.count);
        [ids2Del release];
        [listAll release];
    }
    return self;
}

- (void) dealloc {
    PP_RELEASE(httpSort);
    PP_RELEASE(listNext);
    PP_RELEASE(setShow);
    PP_RELEASE(dicLocal);
    PP_RELEASE(dbSort);
    PP_RELEASE(listShow);
    [super dealloc];
}

-(void)removeLikeState {
    for( JokeModel * one in [dicLocal allValues] ){
        one.liked = -1;
        one.unliked = -1;
    }
    [[DBManager sharedInstance] removeJokeLikeState:dbSort];
}

-(void)expJokes:(ASIHTTPRequest *)request :(BOOL)textOnly :(BOOL)increase :(NSMutableArray *)listHttp {
    NSString *tResponseStr = [request responseString];
    //    Log(@"res: %@",tResponseStr);
    SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
    id tJsonObjects = [tJsonParser objectWithString:tResponseStr];
    [tJsonParser release], tJsonParser = nil;
    if ([tJsonObjects isKindOfClass:[NSDictionary class]]){
        NSMutableArray *tJokesStr = [(NSDictionary *)tJsonObjects mutableArrayValueForKey:@"jokes"];
        //        Log(@"get : %d",tJokesStr.count);
        for (NSDictionary *tJokeStr in tJokesStr) {
            if(increase){
                backIndex++;
            }
            JokeModel *tJokeModel = [[JokeModel alloc] init];
            NSString *jokeId = [[tJokeStr objectForKey:@"Jokeid"] stringValue];
            if(jokeId<=0){
                Log(@"pass : jokeId=%@",jokeId);
                continue;
            }
            [tJokeModel setJokeId:jokeId];
            [tJokeModel setJokeTime:[tJokeStr objectForKey:@"created"]];
            [tJokeModel setJokeText:[tJokeStr objectForKey:@"content"]];
            NSString *jokeImgUrl = [tJokeStr objectForKey:@"uri"];
            if(jokeImgUrl.length==0){
                [tJokeModel setJokeImgUrl:jokeImgUrl];
            }else{
                if (textOnly) {
                    Log(@"pass because textonly");
                    continue;
                }
                if([jokeImgUrl hasPrefix:@"http"]){
                    [tJokeModel setJokeImgUrl:jokeImgUrl];
                }else{
                    [tJokeModel setJokeImgUrl:COMPLEMENTED_URL(jokeImgUrl)];
                }
            }
            [tJokeModel setGoodNum:[[tJokeStr objectForKey:@"like_count"] intValue]];
            [tJokeModel setBadNum:[[tJokeStr objectForKey:@"unlike_count"] intValue]];
            [tJokeModel setReplyNum:[[tJokeStr objectForKey:@"comment_count"] intValue]];
            [tJokeModel setUserId:[[tJokeStr objectForKey:@"Userid"] intValue]];
            [tJokeModel setUserName:[tJokeStr objectForKey:@"user_name"]];
            NSString *userIconUrl = [tJokeStr objectForKey:@"user_cover_url"];
            if([userIconUrl hasPrefix:@"http"]||userIconUrl.length==0){
                [tJokeModel setUserIconUrl:userIconUrl];
            }else{
                [tJokeModel setUserIconUrl:COMPLEMENTED_URL(userIconUrl)];
            }
            [listHttp addObject:tJokeModel];
            [tJokeModel release];
        }
        Log(@"get %d",listHttp.count);
    }else{
        Log(@"get 0");
    }
}

-(BOOL)saveFullJoke:(JokeModel *)pJoke {
    BOOL res = NO;
    JokeModel *tmp = [pJoke copy];
    if(tmp.jokeImgUrl.length != 0){
//        NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:tmp.jokeImgUrl]];
//        if(imgData!=nil){
//            res = YES;
//            if([[tmp.jokeImgUrl lowercaseString] hasSuffix:@"gif"]){
//                tmp.jokeGifData = imgData;
//            }else{
//                tmp.jokeGifData = nil;
//            }
//            UIImage *tJokeImgFull = [[UIImage alloc] initWithData:imgData];
//            UIImage *tJokeImgThumnail = [self thumbnailOfImage:tJokeImgFull withWidth:THUMBNAILWIDTH withHeight:THUMBNAILHEIGHT];
//            tmp.jokeImgFull = tJokeImgFull;
//            tmp.jokeImgThumbnail = tJokeImgThumnail;
//            [tJokeImgFull release]; //内存检测
//        }
        res = YES;
    }else{
        res = YES;
    }
    if( res ){
        [[DBManager sharedInstance] saveJoke:dbSort :tmp];
        [tmp release];
    }
    return res;
}

-(void)merge:(int)startIndex :(NSMutableArray *)listHttp :(NSMutableArray *)listNew {
    int index = startIndex;
    int count = listHttp.count-1+startIndex;
    for (JokeModel *one in listHttp) {
        JokeModel *hit = [dicLocal objectForKey:one.jokeId];
        if( hit == nil ) { // 本地不含
            BOOL oneNewSaved = NO;
            one.jokeIndex = index;
            Log(@"(%d/%d) loading : %@ - %@",one.jokeIndex,count,one.jokeId,one.jokeImgUrl);
            oneNewSaved = [self saveFullJoke:one];
            if( oneNewSaved ){
                Log(@"(%d/%d) loading : %@ - done",one.jokeIndex,count,one.jokeId);
                [dicLocal setObject:one forKey:one.jokeId];
                [listNew addObject:one];
                ++index;
            }else{
                Log(@"(%d/%d) loading : %@ - failed",one.jokeIndex,count,one.jokeId);
            }
        }else{ //本地已经存在
            BOOL changed = NO;
            if( hit.jokeIndex != index ){
                hit.jokeIndex = index;
                changed = YES;
            }
            if( hit.goodNum != one.goodNum ){
                hit.goodNum = one.goodNum;
                changed = YES;
            }
            if( hit.badNum != one.badNum ){
                hit.badNum = one.badNum;
                changed = YES;
            }
            if( hit.replyNum != one.replyNum ){
                hit.replyNum = one.replyNum;
                changed = YES;
            }
            if( changed ){
                [[DBManager sharedInstance] updateJoke:dbSort :hit];
            }
            [listNew addObject:hit];
            Log(@"(%d/%d) exist : %@",hit.jokeIndex,count,hit.jokeId);
            ++index;
        }
    }
}

#pragma mark –
#pragma mark ------getStart------

-(void)getStartAsync:(BOOL)textOnly {
    if( started ){
        return;
    }
    started = YES;
    @synchronized(self){
        self.gettingNew = YES;
        self.gettingNext = YES;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        int newCount = [self httpStartSync:NO];
        if(newCount>0){
            [delegate JMloadNew:self :newCount];
        }
        @synchronized(self){
            self.gettingNew = NO;
            self.gettingNext = NO;
        }
        [delegate JMloadNew:self :0];
        [self httpNextSync:NO];
    });
}

-(int)httpStartSync:(BOOL)textOnly {
    int tIndex = listShow.count;
    if(tIndex==0){
        tIndex = DEFAULTLIMIT;
    }
    
    NSString *url;
    if(textOnly){
        url = JOKE_INIT_TEXTONLY_URL(httpSort, 0, tIndex);
    }else{
        url = JOKE_INIT_NOTEXTONLY_URL(httpSort, 0, tIndex);
    }
    
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
//    request.userAgentString = @"lxh_app2_100";
//    [request setRequestMethod:@"GET"];
//    [request setAllowCompressedResponse:YES];
//    [request setDelegate:self];
////    [request setDidFinishSelector:@selector(requestNewDone:)];
////    [request setDidFailSelector:@selector(requestNewFaild:)];
//    [request startSynchronous];

    ASIHttpRequset_GET(url, NO);
    
    NSError *err = [request error];
    int newCount = 0;
    if(!err){
        if( listShow.count == 0 ){
            [self requestInitDone:request :textOnly];
        }else{
            newCount = [self requestRefreshDone:request :textOnly];
        }
    }else{
        [self requestFailed:request :@"httpStart"];
    }
    return newCount;
}

- (int)requestInitDone:(ASIHTTPRequest *)request :(BOOL)textOnly {
    int newCount = 0;
    NSMutableArray *listHttp = [[NSMutableArray alloc] init];
    [self expJokes:request :textOnly :YES :listHttp];
    for (JokeModel *one in listHttp) {
        BOOL oneNewSaved = NO;
        one.jokeIndex = newCount;
        Log(@"(%d/%d) loading : %@ - %@",one.jokeIndex,listHttp.count-1,one.jokeId,one.jokeImgUrl);
        oneNewSaved = [self saveFullJoke:one];
        if( oneNewSaved ){
            Log(@"(%d/%d) loading : %@ - done",one.jokeIndex,listHttp.count-1,one.jokeId);
            [dicLocal setObject:one forKey:one.jokeId];
            [listShow addObject:one];
            [setShow addObject:one.jokeId];
            ++newCount;
            [delegate JMloadNext:self :1];
        }else{
            Log(@"(%d/%d) loading : %@ - failed",one.jokeIndex,listHttp.count-1,one.jokeId);
        }
    }
    [listHttp release];
    return newCount;
}

- (int)requestRefreshDone:(ASIHTTPRequest *)request :(BOOL)textOnly {
    NSMutableArray *listHttp = [[NSMutableArray alloc] init];
    [self expJokes:request :textOnly :YES :listHttp];
    
    NSMutableSet *setHttp = [[NSMutableSet alloc] init];
    for( JokeModel *one in listHttp ){
        [setHttp addObject:one.jokeId];
    }
    
    int newCount = listHttp.count;
    for( JokeModel *one in listShow ){
        if( ![setHttp containsObject:one.jokeId]){ //显示列表中不含
            JokeModel *tmp = [[one copy] autorelease];
            [listHttp addObject:tmp];
            [setHttp addObject:tmp.jokeId];
        }else{
            newCount--;
        }
    }
    
    NSMutableArray *listNew = [[NSMutableArray alloc] init];
    [self merge:0 :listHttp :listNew];
    
    [listShow removeAllObjects];
    [setShow removeAllObjects];
    for( JokeModel *one in listNew ){
        [listShow addObject:one];
        [setShow addObject:one.jokeId];
    }
    
    int startIndex = listShow.count;
    NSMutableArray *newListNext = [[NSMutableArray alloc] init];
    for(JokeModel *one in listNext){
        if( ![setShow containsObject:one.jokeId] ){
            BOOL changed = NO;
            if( one.jokeIndex != startIndex ){
                one.jokeIndex = startIndex;
                changed = YES;
            }
            if( changed ){
                [[DBManager sharedInstance] updateJoke:dbSort :one];
            }
            [newListNext addObject:one];
            startIndex++;
        }
    }
    [listNext removeAllObjects];
    for( JokeModel *one in newListNext ){
        [listNext addObject:one];
    }
    
    [listHttp release];
    [setHttp release];
    [listNew release];
    [newListNext release];
    return newCount;
}

#pragma mark –
#pragma mark ------getNewAndNext------

-(void)getNewAndNextAsync:(BOOL)textOnly {
    @synchronized(self){
        if(self.gettingNew || self.gettingNext){
            return;
        }
        self.gettingNew = YES;
        self.gettingNext = YES;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        int newCount = [self httpNewSync:NO];
        int nextCount = 0;
        if(listNext.count > 0){
            for( JokeModel *one in listNext ){
                if( [setShow containsObject:one.jokeId] ){
                    continue;
                }
                ++nextCount;
                [listShow addObject:one];
                [setShow addObject:one.jokeId];
            }
            [listNext removeAllObjects];
            Log(@"new : %d, next : %d",newCount,nextCount);
            [delegate JMloadNewAndNext:self :newCount :nextCount];
            @synchronized(self){
                self.gettingNew = NO;
                self.gettingNext = NO;
            }
            [self httpNextSync:NO];
        }else{
            [self httpNextSync:NO];
            int nextCount = 0;
            for( JokeModel *one in listNext ){
                if( [setShow containsObject:one.jokeId] ){
                    continue;
                }
                ++nextCount;
                [listShow addObject:one];
                [setShow addObject:one.jokeId];
            }
            [listNext removeAllObjects];
            Log(@"new : %d, next : %d",newCount,nextCount);
            @synchronized(self){
                self.gettingNew = NO;
                self.gettingNext = NO;
            }
            [delegate JMloadNewAndNext:self :newCount :nextCount];
            [self httpNextSync:NO];
        }
    });
}

#pragma mark –
#pragma mark ------getNew------

-(void)getNewAsync:(BOOL)textOnly {
    @synchronized(self){
        if(self.gettingNew){
            return;
        }
        self.gettingNew = YES;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        int newCount = [self httpNewSync:NO];
        if(newCount>0){
            [delegate JMloadNew:self :newCount];
        }
        @synchronized(self){
            self.gettingNew = NO;
        }
        [delegate JMloadNew:self :0];
    });
}

-(int)httpNewSync:(BOOL)textOnly {
    int newCount = 0;
    int tIndex = listShow.count;
    if(tIndex<DEFAULTLIMIT){
        tIndex = DEFAULTLIMIT;
    }
    if(tIndex>LOCALLIMIT){
        tIndex=LOCALLIMIT;
    }
    
    NSString *url;
    if(textOnly){
        url = JOKE_INIT_TEXTONLY_URL(httpSort, 0, tIndex);
    }else{
        url = JOKE_INIT_NOTEXTONLY_URL(httpSort, 0, tIndex);
    }
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
//    request.userAgentString = @"lxh_app2_100";
//    [request setRequestMethod:@"GET"];
//    [request setAllowCompressedResponse:YES];
//    [request setDelegate:self];
////    [request setDidFinishSelector:@selector(requestNewDone:)];
////    [request setDidFailSelector:@selector(requestNewFaild:)];
//    [request startSynchronous];
    ASIHttpRequset_GET(url, NO);
    NSError *err = [request error];
    if(!err){
        newCount = [self requestNewDone:request :textOnly];
    }else{
        [self requestFailed:request :@"httpNew"];
    }
    return newCount;
}

- (int)requestNewDone:(ASIHTTPRequest *)request :(BOOL)textOnly {
    NSMutableArray *listHttp = [[NSMutableArray alloc] init];
    [self expJokes:request :textOnly :NO :listHttp];
    
    NSMutableSet *setHttp = [[NSMutableSet alloc] init];
    for( JokeModel *one in listHttp ){
        [setHttp addObject:one.jokeId];
    }
    
    int newCount = listHttp.count;
    for( JokeModel *one in listShow ){
        if( ![setHttp containsObject:one.jokeId]){ //显示列表中不含
            JokeModel *tmp = [[one copy] autorelease];
            [listHttp addObject:tmp];
            [setHttp addObject:tmp.jokeId];
        }else{
            newCount--;
        }
    }
    
    NSMutableArray *listNew = [[NSMutableArray alloc] init];
    [self merge:0 :listHttp :listNew];
    
    [listShow removeAllObjects];
    [setShow removeAllObjects];
    for( JokeModel *one in listNew ){
        [listShow addObject:one];
        [setShow addObject:one.jokeId];
    }
    
    int startIndex = listShow.count;
    NSMutableArray *newListNext = [[NSMutableArray alloc] init];
    for(JokeModel *one in listNext){
        if( ![setShow containsObject:one.jokeId] ){
            BOOL changed = NO;
            if( one.jokeIndex != startIndex ){
                one.jokeIndex = startIndex;
                changed = YES;
            }
            if( changed ){
                [[DBManager sharedInstance] updateJoke:dbSort :one];
            }
            [newListNext addObject:one];
            startIndex++;
        }
    }
    [listNext removeAllObjects];
    for( JokeModel *one in newListNext ){
        [listNext addObject:one];
    }
    
    [listHttp release];
    [setHttp release];
    [listNew release];
    [newListNext release];
    return newCount;
}

#pragma mark –
#pragma mark ------getNext------

-(void)getNextAsync:(BOOL)textOnly {
    @synchronized(self){
        if(self.gettingNext){
            return;
        }
        self.gettingNext = YES;
    }
    Log(@"next : %d",listNext.count);
    if(listNext.count > 0){
        int nextCount = 0;
        for( JokeModel *one in listNext ){
            if( [setShow containsObject:one.jokeId] ){
                continue;
            }
            ++nextCount;
            [listShow addObject:one];
            [setShow addObject:one.jokeId];
        }
        [listNext removeAllObjects];
        @synchronized(self){
            self.gettingNext = NO;
        }
        [delegate JMloadNext:self :nextCount];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self httpNextSync:NO];
        });
    }
}

-(void)httpNextSync:(BOOL)textOnly {
    NSString *url;
    if(textOnly){
        url = JOKE_INIT_TEXTONLY_URL(httpSort, backIndex, DEFAULTLIMIT);
    }else{
        url = JOKE_INIT_NOTEXTONLY_URL(httpSort, backIndex, DEFAULTLIMIT);
    }
    
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
//    request.userAgentString = @"lxh_app2_100";
//    [request setRequestMethod:@"GET"];
//    [request setAllowCompressedResponse:YES];
//    [request setDelegate:self];
//    //[request setDidFinishSelector:@selector(requestNextDone:)];
//    //[request setDidFailSelector:@selector(requestNextFaild:)];
//    [request startSynchronous];
    ASIHttpRequset_GET(url, NO);
    NSError *err = [request error];
    if(!err){
        [self requestNextDone:request :textOnly];
    }else{
        [self requestFailed:request :@"httpNext"];
    }
    @synchronized(self){
        if(!self.gettingNext){
            return;
        }
    }
    int nextCount = 0;
    for( JokeModel *one in listNext ){
        if( [setShow containsObject:one.jokeId] ){
            continue;
        }
        ++nextCount;
        [listShow addObject:one];
        [setShow addObject:one.jokeId];
    }
    [listNext removeAllObjects];
    @synchronized(self){
        self.gettingNext = NO;
    }
    [delegate JMloadNext:self :nextCount];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self httpNextSync:NO];
    });
}

- (int)requestNextDone:(ASIHTTPRequest *)request :(BOOL)textOnly {
    
    NSMutableArray *listHttp = [[NSMutableArray alloc] init];
    [self expJokes:request :textOnly :YES :listHttp];
    
    int lastIndex = 0;
    JokeModel *last = [listShow lastObject];
    if( last != nil ){
        lastIndex = last.jokeIndex+1;
    }
    
    NSMutableArray *tListNext = [[NSMutableArray alloc] init];
    [self merge:lastIndex :listHttp :tListNext];
    
    int nextCount = 0;
    for( JokeModel *one in tListNext ){
        if( ![setShow containsObject:one.jokeId]){ //显示列表中不含
            [listNext addObject:one];
            nextCount++;
        }
    }
    
    [listHttp release];
    [tListNext release];
    return nextCount;
}

#pragma mark –
#pragma mark ------isLiked / isUnliked------

-(int)httpIsLikedSync:(NSString *)jokeId
{
    NSString *url = JOKE_LIKE_URL(jokeId);
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
//    request.userAgentString = @"lxh_app2_100";
//    [request setRequestMethod:@"GET"];
//    [request setAllowCompressedResponse:YES];
//    [request addRequestHeader:@"COOKIE" value:[NSString stringWithFormat:@"webpy_session_id=%@",[UserManager sharedInstance].sessionId] ];
//    [request setDelegate:self];
//    [request startSynchronous];
    ASIHttpRequset_GET(url, YES);

    BOOL isLiked = NO;
    NSError *err = [request error];
    if(!err){
        isLiked = [self requestIsLikedFinished:request];
    }else{
        [self requestFailed:request :@"httpIsLiked"];
        return -1;
    }
    return isLiked;
}

- (int)requestIsLikedFinished:(ASIHTTPRequest *)request
{
    NSString *tResponseStr = [request responseString];
    //    Log(@"res : %@",tResponseStr);
    
    SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
    id tJsonObjects = [tJsonParser objectWithString:tResponseStr];
    [tJsonParser release], tJsonParser = nil;
    BOOL isLiked = NO;
    if ([tJsonObjects isKindOfClass:[NSDictionary class]]){
        isLiked = [[tJsonObjects objectForKey:@"exists"] boolValue];
    }
    Log(@"isLiked : %@",isLiked?@"YES":@"NO");
    return isLiked?1:0;
}

-(int)httpIsUnlikedSync:(NSString *)jokeId
{
    NSString *url = JOKE_UNLIKE_URL(jokeId);
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
//    request.userAgentString = @"lxh_app2_100";
//    [request setRequestMethod:@"GET"];
//    [request setAllowCompressedResponse:YES];
//    [request addRequestHeader:@"COOKIE" value:[NSString stringWithFormat:@"webpy_session_id=%@",[UserManager sharedInstance].sessionId] ];
//    [request setDelegate:self];
//    [request startSynchronous];
    
    ASIHttpRequset_GET(url, YES);
    BOOL isLiked = NO;
    NSError *err = [request error];
    if(!err){
        isLiked = [self requestIsUnlikedFinished:request];
    }else{
        [self requestFailed:request :@"httpIsUnliked"];
    }
    return isLiked;
}

- (int)requestIsUnlikedFinished:(ASIHTTPRequest *)request
{
    NSString *tResponseStr = [request responseString];
    //    Log(@"res : %@",tResponseStr);
    
    SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
    id tJsonObjects = [tJsonParser objectWithString:tResponseStr];
    [tJsonParser release], tJsonParser = nil;
    BOOL isLiked = NO;
    if ([tJsonObjects isKindOfClass:[NSDictionary class]]){
        isLiked = [[tJsonObjects objectForKey:@"exists"] boolValue];
    }
    Log(@"isLiked : %@",isLiked?@"YES":@"NO");
    return isLiked?1:0;
}

#pragma mark –
#pragma mark ------getReply------

-(NSMutableArray *)httpGetReplySync:(NSString *)jokeId
{
    NSString *url = JOKE_REPLY_URL(jokeId);
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
//    request.userAgentString = @"lxh_app2_100";
//    [request setRequestMethod:@"GET"];
//    [request setAllowCompressedResponse:YES];
//    [request setDelegate:self];
//    [request startSynchronous];
    ASIHttpRequset_GET(url, NO);
    NSError *err = [request error];
    if(!err){
        return [self requestGetReplyFinished:request];
    }else{
        [self requestFailed:request :@"httpGetReply"];
        return nil;
    }
}

- (NSMutableArray *)requestGetReplyFinished:(ASIHTTPRequest *)request
{
    // 当以文本形式读取返回内容时用这个方法
    NSString *tResponseStr = [request responseString];
    //    Log(@"res : %@",tResponseStr);
    
    SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
    id tJsonObjects = [tJsonParser objectWithString:tResponseStr];
    [tJsonParser release], tJsonParser = nil;
    if ([tJsonObjects isKindOfClass:[NSDictionary class]]){
        NSMutableArray *tReplies = [(NSDictionary *)tJsonObjects mutableArrayValueForKey:@"comments"];
        //        Log(@"replies.count : %d",tReplies.count);
        NSMutableArray *resReplies = [[[NSMutableArray alloc] init] autorelease];
        for (NSDictionary *tJoke in tReplies)
        {
            NSDictionary *tAuthor = [tJoke objectForKey:@"author"];
            JokeReplyModel *tReply = [[[JokeReplyModel alloc] init] autorelease];
            [tReply setReplyName:[tAuthor objectForKey:@"username"]];
            [tReply setReplyText:[tJoke objectForKey:@"content"]];
            [resReplies addObject:tReply];
        }
        return resReplies;
    }
    return nil;
}

#pragma mark –
#pragma mark ------like / unlike------

-(BOOL)httpLikedSync:(NSString *)jokeId {
//    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:JOKE_WHETHER_LIKED_URL]];
//    request.userAgentString = @"lxh_app2_100";
//    [request setAllowCompressedResponse:YES];
//    [request addRequestHeader:@"Cookie" value:[NSString stringWithFormat:@"webpy_session_id=%@",[UserManager sharedInstance].sessionId] ];
//    [request setPostValue:jokeId forKey:@"joke_id"];
//    [request setPostValue:@"like_joke" forKey:@"item_type"];
//    [request setDelegate:self];
//    [request startSynchronous];
    
    ASIFormDataRequest_POST(JOKE_WHETHER_LIKED_URL);
    [request setPostValue:jokeId forKey:@"joke_id"];
    [request setPostValue:@"like_joke" forKey:@"item_type"];
    [request setDelegate:self];
    [request startSynchronous];

    NSError *err = [request error];
    if(!err){
        return [self requestLikeFinished:request];
    }else{
        [self requestFailed:request :@"httpLike"];
        return NO;
    }
}

- (BOOL)requestLikeFinished:(ASIHTTPRequest *)request {
    NSString *tResponseStr = [request responseString];
    Log(@"res : %@",tResponseStr);
    
    SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
    id tJsonObjects = [tJsonParser objectWithString:tResponseStr];
    [tJsonParser release], tJsonParser = nil;
    BOOL isSucc = NO;
    if ([tJsonObjects isKindOfClass:[NSDictionary class]]){
        isSucc = [[tJsonObjects objectForKey:@"success"] boolValue];
    }
    Log(@"isSucc : %@",isSucc?@"YES":@"NO");
    return isSucc;
}

-(BOOL)httpUnlikedSync:(NSString *)jokeId {
//    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:JOKE_WHETHER_LIKED_URL]];
//    request.userAgentString = @"lxh_app2_100";
//    [request setAllowCompressedResponse:YES];
//    [request addRequestHeader:@"Cookie" value:[NSString stringWithFormat:@"webpy_session_id=%@",[UserManager sharedInstance].sessionId] ];
//    [request setPostValue:jokeId forKey:@"joke_id"];
//    [request setPostValue:@"unlike_joke" forKey:@"item_type"];
//    [request setDelegate:self];
//    [request startSynchronous];
//    
    
    ASIFormDataRequest_POST(JOKE_WHETHER_LIKED_URL);
    [request setPostValue:jokeId forKey:@"joke_id"];
    [request setPostValue:@"unlike_joke" forKey:@"item_type"];
    [request setDelegate:self];
    [request startSynchronous];
    
    NSError *err = [request error];
    if(!err){
        return [self requestUnlikeFinished:request];
    }else{
        [self requestFailed:request :@"httpUnlike"];
        return NO;
    }
}

- (BOOL)requestUnlikeFinished:(ASIHTTPRequest *)request {
    NSString *tResponseStr = [request responseString];
    Log(@"res : %@",tResponseStr);
    
    SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
    id tJsonObjects = [tJsonParser objectWithString:tResponseStr];
    [tJsonParser release], tJsonParser = nil;
    BOOL isSucc = NO;
    if ([tJsonObjects isKindOfClass:[NSDictionary class]]){
        isSucc = [[tJsonObjects objectForKey:@"success"] boolValue];
    }
    Log(@"isSucc : %@",isSucc?@"YES":@"NO");
    return isSucc;
}

#pragma mark –
#pragma mark ------requestFailed------

- (void)requestFailed:(ASIHTTPRequest *)request :(NSString *)type {
    Log(@"%@ failed : %@",type,[[request error] description]);
}

#pragma mark –
#pragma mark ------thumbnail------

- (UIImage*)thumbnailOfImage:(UIImage*)image withWidth:(float)resWidth withHeight:(float)resHeight
{
    if(!image){
        return nil;
    }
    CGImageRef imageRef = [image CGImage];
    float _width = CGImageGetWidth(imageRef);
    float _height = CGImageGetHeight(imageRef);
//    Log(@"test1: %f x %f",_width,_height);
    UIImage *thumb;
    if(_width<resWidth && _height<resHeight){
        thumb = [image copy];
        return thumb;
    }else{
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
        float scaleWidth = resWidth/_width;
        float scaleHeight = resHeight/_height;
        float scaleMin = MAX(scaleWidth, scaleHeight);
        UIImage *scaleImg = [self resizeImage:image withScale:scaleMin];
//        CGImageRef scaleImageRef = [scaleImg CGImage];
//        Log(@"test2: %zu x %zu",CGImageGetWidth(scaleImageRef),CGImageGetHeight(scaleImageRef));
        CGRect rect = CGRectMake(0, 0, resWidth, resHeight);//创建矩形框
//        Log(@"test3: %f x %f",rect.size.width,rect.size.height);
        UIImage *subImage = [self cutImage:scaleImg withRect:rect];
//        CGImageRef subImageRef = [subImage CGImage];
//        Log(@"test4: %zu x %zu",CGImageGetWidth(subImageRef),CGImageGetHeight(subImageRef));
        thumb = [subImage copy];
        [pool release];
        return [thumb autorelease];
    }
}

- (UIImage *)resizeImage:(UIImage *)image withScale:(float)scaleSize {
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

- (UIImage *)cutImage:(UIImage *)image withRect:(CGRect)rect {
    UIImage * subImage = [UIImage imageWithCGImage:CGImageCreateWithImageInRect([image CGImage], rect)];
    return subImage;
}

-(void)clearJokeData {
    PP_RELEASE(listNext);
    PP_RELEASE(setShow);
    PP_RELEASE(dicLocal);
    PP_RELEASE(listShow);
    PP_RELEASE(dbSort);
}

@end
